﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dacli.modelos.dao
{
    class FacturaDAO : EntidadDao
    {
        public Factura factura;
        public FacturaDAO() : base("facturas") 
        { 

        }
        public Factura asignarId(long id)
        {
            this.consultar("id=" + id);
            return this.factura;
        }

        public override long incluir()
        {
            string sql = "INSERT INTO " + this.tabla + " (formatado, numero, fecha) values" +
            "('" + factura.getFormateado() + "'," + factura.numero + ",now())";
            long facturaResult = conexion.ejecutar(sql);
            if (facturaResult == -1) new NotSupportedException();
            factura.id = facturaResult;
            factura.fecha = DateTime.Now;
            return facturaResult;
        }

        public override long modificar()
        {
            throw new NotImplementedException();
        }

        public override long eliminar()
        {
            throw new NotImplementedException();
        }

        public override bool consultar(string filtro)
        {
            string sql = "SELECT * FROM " + this.tabla + " WHERE " + filtro;
            System.Data.SqlClient.SqlDataReader reader = conexion.consultar(sql);
            if (reader.Read())
            {
                if (factura == null)
                {
                    factura = new Factura();
                }
                factura.numero = reader.GetInt32(reader.GetOrdinal("numero"));
                factura.id = reader.GetInt32(reader.GetOrdinal("id"));
                factura.formatado = reader.GetString(reader.GetOrdinal("formatado"));
                factura.fecha = reader.GetDateTime(reader.GetOrdinal("fecha"));               
                return true;
            }
            return false;
        }

        public int getMaxFactura()
        {
            string sql = "SELECT MAX(numero) FROM facturas";
            int numFactura = modelos.clases.Configuraciones.facturaInicial;
            System.Data.SqlClient.SqlDataReader reader = conexion.consultar(sql);
            if (reader.Read())
            {
                var a = reader.GetValue(0);
                if (a.ToString() != "")
                    numFactura = reader.GetInt32(0) + 1;
            }
            return numFactura;
        }
    }
}
